package com.qqtop10.manager.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qqtop10.manager.dao.AddressMapper;
import com.qqtop10.manager.model.Address;
import com.qqtop10.manager.model.Interval;
import com.qqtop10.manager.service.AddressService;

@Service("addressService")
public class AddressServiceImpl extends BaseService implements AddressService {

	@Autowired
	private AddressMapper addressMapper;

	@Override
	public List<Address> tree(Address input) {
		return addressMapper.tree(input);
	}

	@Override
	public Address get(Address input) {
		return addressMapper.get(input);
	}

	@Override
	public boolean delete(Address input) {
		if (!canDelete(input)) {
			throw new RuntimeException("不能删除存在子级的节点。");
		}
		return addressMapper.delete(input) != 0;
	}

	@Override
	public boolean add(Address input) {
		if (input.getParent_id() == null) {
			throw new NullPointerException("parent_id");
		} else if (input.getParent_id() == 100000) {
			input.setId(newId(100000, 999999) / 10000 * 10000 + 10000);
		} else if (input.getParent_id() % 100 != 0) {
			throw new RuntimeException("暂不能为'区'级目录添加子级。");
		} else if (input.getParent_id() % 10000 != 0) {
			input.setId(newId(input.getParent_id(), input.getParent_id() + 99) + 1);
		} else if (input.getParent_id() % 1000000 != 0) {
			input.setId(newId(input.getParent_id(), input.getParent_id() + 9999) / 100 * 100 + 100);
		} else {
			throw new RuntimeException("Unknow exception.");
		}
		return addressMapper.add(input) != 0;
	}

	@Override
	public boolean update(Address input) {
		return addressMapper.update(input) != 0;
	}

	@Override
	public boolean setParent(Address input) {
		if (isRoot(input)) {
			return false;
		}
		return addressMapper.setParent(input) != 0;
	}

	@Override
	public boolean isRoot(Address input) {
		return input.getId() == 100000;
	}

	private int newId(int min, int max) {
		return addressMapper.newId(new Interval<Integer>(min, max));
	}

	private boolean canDelete(Address input) {
		return addressMapper.canDelete(input) != 0;
	}

	@Override
	public Address selectByFullName(String fullName) {
		return addressMapper.selectByFullName(fullName);
	}

	@Override
	public Address selectByShortName(String shortName) {
		return addressMapper.selectByShortName(shortName);
	}
}
